package com.marketapp.service;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.marketapp.dao.IUserDao;
import com.marketapp.domain.UserInfo;
import com.marketapp.domain.UserRole;
import com.marketapp.helper.DaoException;
import com.marketapp.helper.ServiceException;
import com.marketapp.util.StringUtil;

public class UserServiceImpl implements IUserService {
	
	@Autowired
	IUserDao userDao;
	
	public IUserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public UserInfo getUserByName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Set<UserRole> getUserAuthorities(UserInfo userInfo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.READ_COMMITTED)
	public void createUser(UserInfo userInfo) throws ServiceException {
		try {
			userInfo.setAdmin(false);
			userInfo.setEnabled(1);
			
			/*Set User Roles*/
			UserRole roleUser = new UserRole("ROLE_USER");
			roleUser.setUserInfo(userInfo);
			UserRole roleGuest = new UserRole("ROLE_GUEST");
			roleGuest.setUserInfo(userInfo);
			Set<UserRole> userRoles = new HashSet<UserRole>();
			userRoles.add(roleUser);
			userRoles.add(roleGuest);
			userInfo.setUserRoles(userRoles);
			
			userDao.createUser(userInfo);
		} catch (DaoException e) {
			throw new ServiceException("Error: User cannot be saved", e.getCause());
		}
		
	}

	@Override
	public boolean checkifUserExists(String userName) throws ServiceException {
		try {
			UserInfo userInfo = userDao.getUserByName(userName);
			if(userInfo!=null){
				return true;
			}
		} catch (DaoException e) {
			throw new ServiceException("Error: Cannot retrieve user details", e.getCause());
		} 
		return false;
	}
}
